import { Message, MessageBox } from 'element-ui'
import uuid from 'uuid'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import store from '@/store'
import { encrypt,decrypt } from '@/utils/SM4'

export let Socket = ''
let setIntervalWesocketPush = null
let socketPending = true
let key_sn = '';
let messView = false

window.websocketUrl = location.protocol === 'https:'
  ? 'wss://localhost:9011'
  : 'ws://localhost:9010';
// window.websocketUrl =  "ws://10.10.11.9:9010"
window.websocketProduct =  "hongke_product_zjg"
// A001（Key 基本信息文件名称）
window.keyBasicFileName = "A001"
// A002（Key 用户授权信息文件名称）
window.keyEmpowerFileName = "A002"
// AA01（Key AA授权点数配置文件）
window.keyAuthorizedPointsFileName = "AA01.hkxdr"
//点数授权类型
window.tallyMethod = "point_authorization"

/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket=() => {
  Socket && Socket.close()
  if (!Socket) {
    // console.log('建立websocket连接')
    Socket = new WebSocket(window.websocketUrl)
    Socket.onopen = onopenWS
    Socket.onmessage = onmessageWS
    Socket.onerror = onerrorWS
    Socket.onclose = oncloseWS
    setTimeout(() => {
      if (Socket.readyState === 0 && socketPending) {
        socketPending = false
        SocketError()
      }
    }, 1000)
  } else {
    // console.log('websocket已连接')
  }
}

/**打开WS之后发送心跳 */
const onopenWS = () => {
  // sendPing()
  sendKeyOnline()
}

/**连接失败重连 */
const onerrorWS = () => {
  Socket.close()
  clearInterval(setIntervalWesocketPush)
  // console.log('连接失败重连中')
  if (Socket.readyState !== 3) {
    Socket = null
    // createSocket()
    SocketError()
  }
}

/**WS数据接收统一处理 */
const onmessageWS = e => {
  // console.log("ws返回-->" + decrypt(e.data))
  window.dispatchEvent(new CustomEvent('onmessageWS', {
    detail: {
      data: decrypt(e.data)
    }
  }))
}

/**
 * 发送数据但连接未建立时进行处理等待重发
 * @param {any} message 需要发送的数据
 */
const connecting = message => {
  setTimeout(() => {
    if (Socket.readyState === 0) {
      connecting(message)
    } else {
      Socket.send(encrypt(JSON.stringify(message)))
    }
  }, 1000)
}

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = message => {
  if (Socket !== null && Socket.readyState === 3) {
    Socket.close()
    // createSocket()
    SocketError()
  } else if (Socket.readyState === 1) {
    // console.log("发送数据-->" + JSON.stringify(message))
    Socket.send(encrypt(JSON.stringify(message)))
  } else if (Socket.readyState === 0) {
    connecting(message)
  }
}

/**断开重连 */
const oncloseWS = () => {
  clearInterval(setIntervalWesocketPush)
  // console.log('websocket已断开')
  if (Socket.readyState !== 2) {
    Socket = null
    // createSocket()
    SocketError()
  }
}
/**发送心跳
 * @param {number} time 心跳间隔毫秒 默认5000
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (time = 5000, ping = 'ping') => {
  clearInterval(setIntervalWesocketPush)
  Socket.send(ping)
  setIntervalWesocketPush = setInterval(() => {
    Socket.send(ping)
  }, time)
}

/**
 * websocket链接失败时提示
 * @constructor
 */
const SocketError = () => {
  /*if (window.location.href.indexOf('hkkeywspulgin') > 0) {
    return
  }
  MessageBox.confirm(
    '<div>未检测到' + window.logoTitle + '的KEY的驱动，请确认是否下载并安装了浏览器驱动。' +
    '<a style=\'color: #409EFF;\' target="_blank" href=\'/hkkeywspulgin\'>立即下载驱动</a></div>'
    , '系统提示', {
      confirmButtonText: '重新检测',
      showCancelButton: false,
      showClose: false,
      closeOnClickModal: false,
      dangerouslyUseHTMLString: true,
      type: 'warning',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '检测中...'
          createSocket()
          setTimeout(() => {
            if (!Socket) {
              Message.warning('未检测到' + window.logoTitle + '的KEY的驱动')
              instance.confirmButtonLoading = false
              instance.confirmButtonText = '重新检测'
            } else {
              if (Socket.readyState === 0) {
                Message.warning('未检测到' + window.logoTitle + '的KEY的驱动')
                instance.confirmButtonLoading = false
                instance.confirmButtonText = '重新检测'
              } else {
                MessageBox.close()
              }
            }
          }, 1500)
        } else {
          MessageBox.close()
        }
      }
    }
  )*/
  // Message.warning('未检测到KEY的驱动，请确认是否下载并安装了浏览器驱动。')
}

/**发送命令--检测key是否插入使用
 * @param {number} time 间隔毫秒 默认5000
 */
export const sendKeyOnline = (time = 3000) => {
  clearInterval(setIntervalWesocketPush)
  sendKeyScan()
  setIntervalWesocketPush = setInterval(() => {
    sendKeyScan()
  }, time)
}

/**
 * 接收消息--控制插key操作
 */

const getsocketData = e => {  // 创建接收消息函数
  const data = e && eval('(' + e.detail.data + ')')
  let resultData = data.result_data
  if (data.cmd_name === 'key_scan') {
    // 判断当前用户是否已登录
    let keySn = Cookies.get('keySn')
    if (getToken() && keySn) {
      if (!resultData.key_sn) {
        messView = true
        MessageBox.confirm(
          '未检测到' + window.logoTitle + '的KEY'
          , '系统提示', {
            confirmButtonText: '重新登录',
            showCancelButton: false,
            showClose: false,
            closeOnClickModal: false,
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.href = '/'
          })
        })

      } else {

        if (resultData.key_sn.split(',').length > 1) {
          messView = true
          MessageBox.confirm(
            '请插入一把KEY进行操作'
            , '系统提示', {
              showConfirmButton: false,
              showCancelButton: false,
              showClose: false,
              closeOnClickModal: false,
              type: 'warning'
            }
          )
        }else{
          key_sn = resultData.key_sn
          if(keySn !== key_sn){
            messView = true
            MessageBox.confirm(
              '当前插入的KEY不是登陆时使用的KEY，请重新登录'
              , '系统提示', {
                confirmButtonText: '重新登录',
                showCancelButton: false,
                showClose: false,
                closeOnClickModal: false,
                type: 'warning'
              }
            ).then(() => {
              store.dispatch('LogOut').then(() => {
                location.href = '/'
              })
            })
          }else{
            // 关闭操作
            if (messView) {
              messView = false
              MessageBox.close()
            }
          }
        }

      }
    }else{
      // 关闭操作
      if (messView) {
        messView = false
        MessageBox.close()
      }
    }
  }
}

/**
 * key业务发送指令--通用--获取key号
 */
const sendKeyScan = () => {
  let sendKeyData = {}
  sendKeyData.cmd_sender = "hongke_product_common"
  sendKeyData.cmd_id = uuid.v4()
  sendKeyData.cmd_name = "key_scan"
  sendKeyData.cmd_data = {}
  sendWSPush(sendKeyData)
}
/**
 * key业务发送指令--已定义产品
 */
const sendKeyProduct = (cmdName, cmdData) => {
  let sendKeyData = {}
  sendKeyData.cmd_sender = window.websocketProduct
  sendKeyData.cmd_id = uuid.v4()
  sendKeyData.cmd_name = cmdName
  sendKeyData.cmd_data = cmdData
  sendWSPush(sendKeyData)
}

export default {
  createSocket, sendWSPush, getsocketData,sendKeyProduct
}
